package com.justgame.project.base.construct;

import com.justgame.project.cloud.common.util.RedisUtils;
import com.justgame.project.cloud.common.constant.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * 向Redis缓存当前微服务下所有的Api地址
 * @author ZhouWeiBo
 * @create 2022/3/16
 */
@Slf4j
@Component
public class RequestMappingPostConstruct {

    @Resource
    private WebApplicationContext webApplicationContext;

    @Resource
    private RedisUtils redisUtils;

    @PostConstruct
    public void urls() {
        /* 缓存所有api路径 */
        RequestMappingHandlerMapping mapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        Set<String> patterns = redisUtils.sGet(Const.KEY_REDIS_API);
        for (RequestMappingInfo info : map.keySet()) {
            PatternsRequestCondition condition = info.getPatternsCondition();
            // 获取url的Set集合，一个方法可能对应多个url
            patterns.addAll(condition.getPatterns());
        }
        redisUtils.sSet(Const.KEY_REDIS_API,patterns);
    }


}
